<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>vue router的编程式导航</title>
    <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    <!-- 导入vue-router文件,为全局的window对象挂载VueRouter构造函数 -->
    <script src="js/vue-router.js"></script>
  </head>
  <body>
    <div id="app">
      <router-link to="/index/1">首页1</router-link>
      <router-link to="/index/2">首页2</router-link>
      <router-link to="/index/3">首页3</router-link>
      <!-- 如果使用命名路由,必须采用动态的赋值 -->
      <router-link :to="{name:'indexName',params:{id:4}}">首页4</router-link>
      <router-link to="/keji">科技</router-link>
      <router-view></router-view>
    </div>
    <script>
      const Index = {
        props: ["id", "username", "age"], //使用props接收路由参数
        template: `
          <div>
             <h1>主页内容:编号值id:{{id}}---{{username}}-----{{age}}</h1>
             <button @click='handle'>跳转到科技</button>
          </div>
          `,
        methods: {
          handle(){
            this.$router.push('/keji');
          }
        },
      };

      const Keji = {
        template: `
        <div>
         <h1>科技内容</h1>
         <button @click='handle'>back</button>
        </div> 
         `,
         methods: {
          handle(){
            this.$router.go(-1);
          }
         },
      };

      //创建路由实例对象
      const router = new VueRouter({
        //配置路由的规则
        routes: [
          { path: "/", redirect: "/index/1" },
          //props设置为true,route.params将会被设置为组件属性
          {
            path: "/index/:id",
            name:'indexName',  //通过name属性为当前的路由规则命名
            component: Index,
            props: (route) => ({
              username: "haoren",
              age: 22,
              id: route.params.id,
            }),
          },
          { path: "/keji", component: Keji },
        ],
      });

      //1. 实例化一个Vue的实例
      let vm = new Vue({
        el: "#app",
        data: {},
        //挂载路由对象
        router: router,
      });
    </script>
  </body>
</html>
